<!--  -->
<template>
  <a-modal
    @cancel="modalClose"
    :visible="visible"
    width="600px"
    :maskClosable="false"
    wrapClassName="teacher-code-modal"
    :footer="null"
    :centered="true"
  >
    <div class="teacher-code-content">
      <div class="buffer">
        <!-- <div class="buffer-desc">
          <div class="buffer-desc-content">{{ voiceResult }}</div>
        </div> -->
        <div class="buffer-item">
          <div class="buffer-item-l">
            <span v-show="voice >= 1"></span>
            <span v-show="voice >= 2"></span>
            <span v-show="voice >= 3"></span>
            <span v-show="voice >= 4"></span>
            <span v-show="voice >= 5"></span>
            <span v-show="voice >= 6"></span>
            <span v-show="voice >= 7"></span>
            <span v-show="voice >= 8"></span>
            <span v-show="voice >= 9"></span>
            <span v-show="voice >= 10"></span>
          </div>
          <div class="buffer-item-r">
            <span v-show="voice >= 1"></span>
            <span v-show="voice >= 2"></span>
            <span v-show="voice >= 3"></span>
            <span v-show="voice >= 4"></span>
            <span v-show="voice >= 5"></span>
            <span v-show="voice >= 6"></span>
            <span v-show="voice >= 7"></span>
            <span v-show="voice >= 8"></span>
            <span v-show="voice >= 9"></span>
            <span v-show="voice >= 10"></span>
          </div>
        </div>
      </div>
      <div class="btn-group">
        <a-button type="primary" block shape="round" @click="confirmClick"
          >完成录音</a-button
        >
      </div>
    </div>
  </a-modal>
</template>

<script>
import { diffStrScore } from "@/utils/tools";
import { uploadAudio } from "@/services/composition.js";
import Recorder from "recorder-core";
import "recorder-core/src/engine/mp3";
import "recorder-core/src/engine/mp3-engine";
import "recorder-core/src/extensions/waveview";
import { Modal } from "ant-design-vue";
import { SUCCESS_CODE } from "@/utils/const";
import { randomArr } from '@/services/composition.js'

export default {
  name: "recordModal",
  components: {
    AModal: Modal,
  },
  data() {
    return {
      code: "",
      asrData: [],
      recIsOpen: false,
      BSync: null,
      isController: false,
      id: "",
      isBuffer: false,
      isVoice: false,
      DB: 0,
      voice: 0,
      socket: null,
      // isFinished: false,
      audio: "",
      recordUrl: "",
      rec: null,
      wave: null,
      recBlob: null,
      recordTransformData: null,
      recordStarted: false,
      voiceResult: "",
      voiceModel: "",
      max_record: 15,
      score: 0, // 分数
    };
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    ok: {
      type: Function,
    },
    title: {
      type: String,
    },
  },
  computed: {},
  watch: {
    DB(newDb) {
      if (+newDb === 0) {
        this.voice = 0;
      } else if (newDb >= 1 && newDb <= 20) {
        // 显示一格音谱
        this.voice = 1;
      } else if (newDb >= 21 && newDb <= 40) {
        this.voice = 2;
        // 显示二格音谱
      } else if (newDb >= 41 && newDb <= 60) {
        this.voice = 3;
        // 显示三格音谱
      } else if (newDb >= 71 && newDb <= 90) {
        this.c = 4;
        // 显示四格音谱
      } else if (newDb >= 91 && newDb <= 120) {
        this.voice = 5;
        // 显示五格音谱
      } else if (newDb >= 121 && newDb <= 140) {
        this.voice = 6;
        // 显示六格音谱
      } else if (newDb >= 141 && newDb <= 160) {
        this.voice = 7;
        // 显示七格音谱
      } else if (newDb >= 161 && newDb <= 180) {
        this.voice = 8;
        // 显示八格音谱
      } else if (newDb >= 181 && newDb <= 200) {
        this.voice = 9;
        // 显示九格音谱
      } else if (newDb > 200) {
        this.voice = 10;
        // 显示全部音谱
      }
    },
    visible(value) {
      if (value === true) {
        this.realTimeAsrInit();
      } else {
        if (this.rec !== null) {
          this.realTimeAsrStop();
          this.rec = null;
        }
      }
    },
  },
  methods: {
    modalClose() {
      this.$emit("update:visible", false);
    },
    randomArr(voiceModel) {
      return randomArr({type: voiceModel})
    },
    confirmClick() {
      this.realTimeAsrStop();
    },
    realTimeAsrInit() {
      console.log('init', '-------------init')
      this.voiceModel = ''
      let that = this;
      !this.rec &&
        (this.rec = Recorder({
          type: "mp3",
          sampleRate: 16000,
          bitRate: 16,
          bufferSize: 4096,
          onProcess: (
            buffers,
            powerLevel,
            bufferDuration,
            bufferSampleRate
          ) => {
            this.recordTransformData = Recorder.SampleData(
              buffers,
              bufferSampleRate,
              16000,
              {
                index: this.recordTransformData
                  ? this.recordTransformData.index
                  : 0,
                offset: this.recordTransformData
                  ? this.recordTransformData.offset
                  : 0.0,
              }
            );
            // 业务处理-start
            let buffer = buffers[buffers.length - 1];
            var maxVal = 0;
            for (var i = 0; i < buffer.length; i++) {
              if (maxVal < buffer[i]) {
                maxVal = buffer[i];
              }
            }
            this.DB = parseInt(maxVal / 100);
            // 业务处理-end
            this.socket.send(this.recordTransformData.data);
            // if (bufferDuration / 1000 > this.min_record) {
            //   this.isStop = false;
            // }
            if (bufferDuration / 1000 >= this.max_record) {
              this.asrSyncStopEvent();
            }
          },
        }));
      if (!that.isController) {
        that.BSync && that.BSync.socket.on("sync:socket", function(data) {
          that.realTimeAsrMessage(data);
        });
        that.BSync && that.BSync.socket.on("sync:cmd", function(data) {
          data.cmd &&
            eval(`typeof ${data.cmd} == 'function' && ${data.cmd}(data)`);
        });
      }
      this.realTimeAsrOpen();
    },
    realTimeAsrOpen(asr = true) {
      if (this.playing || this.defaultPlaying) {
        this.$toast("请先暂停播放读音");
        return;
      }
      // 加锁
      if (this.recordTransformData) return false;
      console.log("正在打开录音组件");
      if (this.recIsOpen) {
        if (asr) return this._realTimeAsrOpen();
        else return false;
      }
      this.rec.open(
        (success) => {
          console.log("rec.open", success);
          this.recIsOpen = true;
          if (this.recIsOpen) {
            if (asr) return this._realTimeAsrOpen();
            else return false;
          }
        },
        (msg, isUserNotAllow) => {
          //用户拒绝未授权或不支持
          this.$toast((isUserNotAllow ? "UserNotAllow，" : "") + "无法录音:" + msg);
        }
      );
    },
    _realTimeAsrOpen() {
      console.log("正在启动转写");
      let that = this;
      this.socket = new WebSocket(
        `wss://vop.baidu.com/realtime_asr?sn=${new Date().getTime()}`,
        "websocket"
      );
      this.socket.addEventListener("open", () => {
        this.socket.send(
          JSON.stringify({
            type: "START",
            data: {
              appid: 21812587,
              appkey: "WzgLZY1Ico79HSU6fzzsG9Ic",
              dev_pid: 17372,
              cuid: "cuid-1",
              format: "pcm",
              sample: 16000,
            },
          })
        );
        this.DB = 0;
        this.isBuffer = true;
        this.isVoice = false;
        this.isStop = true;
        this.rec.start();
      });
      if (that.isController) {
        this.socket.addEventListener("message", (msgevt) => {
          let data = msgevt.data;
          if (data) {
            data = JSON.parse(data);
            if (data.err_no == 0) {
              that.BSync && that.BSync.socket.emit("sync:socket", data);
              that.realTimeAsrMessage(data);
            }
          }
        });
      }
      this.socket.addEventListener("close", (e) => {
        if (e.target.url === this.socket.url) {
          this.asrSyncStopEvent();
        }
        console.log("关闭连接", e);
      });
    },
    _realTimeAsrMessage(data) {
      // 业务处理
      console.log("业务处理.识别数据", data);
      this.voiceModel = data.join(" ");
      this.voiceResult = data.join(" ");
    },
    realTimeAsrMessage(data) {
      console.log(this.asrData, "-=--=-=-");
      console.log("原始数据", data);
      this.asrData[this.asrData.length == 0 ? 0 : this.asrData.length - 1] =
        data.result;
      if (data.type == "FIN_TEXT") {
        this.asrData[this.asrData.length] = "";
      }
      this._realTimeAsrMessage(this.asrData);
    },
    asrSyncStopEvent() {
      let that = this;
      // 传递关闭事件
      if (that.isController) {
        that.BSync && that.BSync.socket.emit("sync:cmd", {
          cmd: "that.realTimeAsrStop",
        });
        that.realTimeAsrStop();
      }
    },
    realTimeAsrStop() {
      // 加锁
      // if (this.bufferDuration / 1000 < this.min_record && this.isStop) {
      //   this.$toast("录音时间太短哦~");
      //   return;
      // }
      if (this.recordTransformData) {
        this.recordTransformData = null;
        this.asrData = [];
        this.isBuffer = false;
        this.isVoice = true;
        this.voiceResult = "";
        console.log(this.voiceModel);
        this.isComplete = true;
        this.isStop = false;
        console.log(this.rec);
        console.log(this.voiceModel);
        this.rec.stop(async (blob, duration) => {
          console.log(33, blob, duration);
          let syncData = await this.randomArr(this.voiceModel)
          console.log(syncData, '-=-=-=-=-|||||||||||||')
          this.voiceModel = syncData.data
          this.$nextTick(async () => {
            console.log(this.voiceModel, '-=-==-123!@#!@#!@#!@#!@')
            this.blob = blob;
            this.score = diffStrScore(this.voiceModel, this.title);
            let formDataBlob = new FormData();
            formDataBlob.append("file", blob, "recorder.mp3");
            formDataBlob.append("type", "grammar");
            await uploadAudio(formDataBlob).then((res) => {
              if (res.code === SUCCESS_CODE) {
                console.log(this, res.data.path);
                this.recordUrl = res.data.path;
              }
            });
            this.$emit("ok", { score: this.score, path: this.recordUrl });
          })
        });
      }
    },
    socketMessage(data) {
      console.log(88888, data);
      if (data.err_no == 0) {
        if (this.isController) {
          this.BSync && this.BSync.socket.emit("sync:socket", data);
        }
        this.voiceResult = data.result;
        this.voiceModel += data.result;
      }
    },
  },
  created() {
    this.BSync = window.isBSync();
    this.isController = window.isController();
    // let that = this;
    // if (!that.isController) {
    //   that.BSync && that.BSync.socket.on("sync:socket", function(data) {
    //     that.socketMessage(data);
    //   });
    // }
  },
  mounted() {},
};
</script>
<style lang="less" scoped>
/* @import url(); 引入公共css类 */

.teacher-code-content {
  padding-top: 30px;
  .teacher-code {
    display: flex;
    border-bottom: 1px solid #dddddd;
    align-items: center;
    input {
      width: 180px;
      padding-left: 36px;
      border: none;
      outline: none;
      font-size: 20px;
    }
  }
  .btn-group {
    margin: 50px auto 0;
    width: 270px;
  }
  .buffer {
    height: 250px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 20px auto; /* no */
    border-radius: 10px;
    z-index: 20;
    &-desc {
      height: 130px;
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #333;
      text-align: left;
      overflow: hidden;
      &-content {
        height: 100%;
        overflow: auto;
        &::-webkit-scrollbar {
          width: 0 !important;
        }
      }
    }
    &-item {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
      margin-top: 20px;
      span {
        display: inline-block;
        width: 2px;
        background: #47cbb3;
        border-radius: 1px;
        margin-right: 5px;
        &:nth-child(1) {
          height: 20px;
        }
        &:nth-child(2) {
          height: 24px;
        }
        &:nth-child(3) {
          height: 28px;
        }
        &:nth-child(4) {
          height: 32px;
        }
        &:nth-child(5) {
          height: 36px;
        }
        &:nth-child(6) {
          height: 36px;
        }
        &:nth-child(7) {
          height: 32px;
        }
        &:nth-child(8) {
          height: 28px;
        }
        &:nth-child(9) {
          height: 24px;
        }
        &:nth-child(10) {
          height: 20px;
        }
      }
    }
    &-btn {
      position: fixed;
      left: 50%;
      bottom: 20px;
      transform: translateX(-50%);
      width: 200px;
      height: 46px;
      line-height: 46px;
      text-align: center;
      font-size: 20px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #fff;
      background: linear-gradient(
        360deg,
        rgba(71, 203, 179, 1) 0%,
        rgba(81, 211, 176, 1) 100%
      );
      box-shadow: 0px 5px 10px rgba(59, 201, 164, 0.3);
      border-radius: 100px;
    }
  }
}
</style>
